package com.peanut.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.peanut.common.Result;
import com.peanut.domain.po.TabUser;
import com.peanut.em.ResultEnum;
import com.peanut.mapper.TabUserMapper;
import com.peanut.service.ManagerService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class ManagerServiceImpl implements ManagerService {

    @Autowired
    private TabUserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Result login(String phone, String code) {

        // 根据手机号到用户表查询是否有记录
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("phone",phone);
        List list = userMapper.selectList(queryWrapper);
        // 判断查询数据是否为空
        if (Objects.isNull(list)) {
            return Result.R(ResultEnum.DATA_NULL);
        }
        // 从redis获取验证码
        String s = String.valueOf(redisTemplate.opsForValue().get(phone));
        // 判断验证码是否正确
        if (!s.equals(code)){
            return Result.R(ResultEnum.CODE_FAULT);
        }
        // 1.获取subject对象
        Subject subject = SecurityUtils.getSubject();
        // 2.将用户数据封装成token对象
        UsernamePasswordToken token = new UsernamePasswordToken(phone, code);
        // 3.调用subject的login方法执行登录逻辑
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            return Result.R(ResultEnum.LOGIN_UNKNOWNACCOUN);
        }catch (IncorrectCredentialsException e) {
            return Result.R(ResultEnum.CODE_FAULT);
        }
        return Result.R(ResultEnum.SUCCESS);
    }


    @Override
    public Result addUser(TabUser user) {
        // 根据手机号到用户表查询是否有记录
        QueryWrapper<TabUser> queryWrapper = new QueryWrapper();
        queryWrapper.eq("phone",user.getPhone());
        List<TabUser> tabUsers = userMapper.selectList(queryWrapper);
        // 判断账户是否已经注册
        if (!CollectionUtils.isEmpty(tabUsers)){
            return Result.R(ResultEnum.REGISTERED);
        }
        userMapper.insert(user);
        return Result.R(ResultEnum.SUCCESS);
    }
}
